//
//  VPTimer.m
//  teacherSecretary
//
//  Created by verne on 16/6/23.
//  Copyright © 2016年 vernepung. All rights reserved.
//

#import "VPTimer.h"
#import "UtilsMacro.h"
@interface VPTimer(){
    dispatch_source_t timer;
}
@end

@implementation VPTimer
- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval totalTimeInterval:(NSTimeInterval)totalTimeInterval{
    self = [super init];
    if (self) {
        if (timeInterval >= totalTimeInterval || timeInterval <= 0){
            NSAssert(NO, @"VPTimer error");
        }
        _timeInterval = timeInterval;
        _totalTimeInterval = totalTimeInterval;
        [self timerInit];
    }
    return self;
}

- (void)timerInit{
    dispatch_queue_t vpTimerQueue = dispatch_queue_create("com.dispatch.vernepung.timer.queue", DISPATCH_QUEUE_CONCURRENT);
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, vpTimerQueue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, _timeInterval * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (_remainingTimeInterval <= 0){
            [self invalidate];
            return ;
        }else{
            if ([self.delegate respondsToSelector:@selector(timerEventHandler:)]){
                @weakify(self);
                dispatch_async(dispatch_get_main_queue(), ^{
                    @strongify(self);
                    [self.delegate timerEventHandler:self];
                });
            }
        }
        _remainingTimeInterval--;
    });
}

- (void)reFire{
    if (timer){
        dispatch_source_cancel(timer);
        _isVaild = NO;
        timer = nil;
    }
    [self timerInit];
    [self fire];
}

- (void)fire{
    if (timer && !_isVaild){
        _isVaild = YES;
        _remainingTimeInterval = _totalTimeInterval;
        dispatch_resume(timer);
    }else{
        [self reFire];
    }
}

- (void)invalidate{
    if (timer){
        dispatch_source_cancel(timer);
        _isVaild = NO;
        timer = nil;
        if ([self.delegate respondsToSelector:@selector(timerCompleted)]){
            dispatch_main_async_safe(^{
                [self.delegate timerCompleted];
            });
        }
    }
}
@end
